// 展示分页信息
$.ajax({
    type: 'get',
    url: '/categories',
    success: function(response) {
        var html = template('categoryTpl', { data: response });
        $('#category').html(html);
    }
});

//
$('#feature').on('change', function() {
    var formData = new FormData();
    formData.append('cover', this.files[0]);
    $.ajax({
        type: 'post',
        url: '/upload',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            console.log(response);
            $('#thumbnail').val(response[0].cover);
        }
    });
});

// 文章添加功能
$('#addForm').on('submit', function() {
    var data = $(this).serialize();
    $.ajax({
        type: 'post',
        url: '/posts',
        data: data,
        success: function() {
            location.href = './posts.html';
        }
    });
    return false;
});

// 文章修改功能
var id = getUrlParams('id');
console.log(id);
if (id != -1) {
    $.ajax({
        type: 'get',
        url: `/posts/${id}`,
        success: function(response) {
            $.ajax({
                type: 'get',
                url: '/categories',
                success: function(categories) {
                    response.categories = categories;
                    var html = template('modifyTpl', response);
                    $('#parentBox').html(html);
                }
            });
        }
    });
    //使用事件委托给修改表单添加提交事件
    $('#parentBox').on('submit', '#modifyForm', function() {
        var data = $(this).serialize();
        var id = $(this).attr('data-id');
        $.ajax({
            type: 'put',
            url: `/posts/${id}`,
            data: data,
            success: function() {
                location.href = './posts.html';
            }
        });
    });
}

function getUrlParams(key) {
    var paramsArr = location.search.substr(1).split('&');
    for (var i = 0; i < paramsArr.length; i++) {
        var arr = paramsArr[i].split('=');
        if (arr[0] == key) {
            return arr[1];
        }
    }
    return -1;
}
